﻿using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

using AD.Pms.Core.ClientApi;
using AD.Pms.Core.EnumHelper;
using AD.Pms.Service.Request;
using AD.Pms.Service.DtoModel;
using AD.Pms.Service.Interfaces;
using AD.Pms.Repository.Repository;

namespace AD.Pms.Service.Manager
{
    /// <summary>
    /// 
    /// </summary>
    public class LoginMgr : Repository<tbl_SysUser>, ILoginService
    {
        #region DI
        private readonly ILogger _logger;
        public LoginMgr(ILogger<LoginMgr> logger)
        {
            _logger = logger;
        }
        #endregion


        /// <summary>
        /// 
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ApiResult<SysAdminMenuDto>> LoginAsync(LoginRequest param)
        {
            var res = new ApiResult<SysAdminMenuDto>();

            try
            {
                var adminModel = new SysAdminMenuDto();
                var user = await Db.Queryable<tbl_SysUser>().FirstAsync(p => p.Phone.Equals(param.Phone));
                if (user == null)
                {
                    res.message = "用户不存在。";
                    return res;
                }
                if (user.IsLocked.Value == 1)
                {
                    res.message = "登录账号被冻结，请联系管理员~";
                    return res;
                }
                user.LoginCount += 1;
                user.LoginTime = DateTime.Now;
                user.LastLoginTime = user.LoginTime;

                // 更新数据


                adminModel.admin = user;
                res.data = adminModel;
            }
            catch (Exception ex)
            {
                res.message = ex.Message;
                res.statusCode = (int)ApiEnum.Error;
                _logger.LogError($"用户登录异常.{ex.Message}", ex);
            }
            return res;
        }


    }
}
